package com.web.music.portal.mvc;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.web.music.interfaces.PersistenceHelper;
import com.web.music.interfaces.SecurityController;
import com.web.music.model.PersistentEntity;
import com.web.music.model.SecuredEntity;

public class DeleteController extends AbstractController {

	// the following three parameters have to be specified in Spring configuration file
	// \lab02-music\lab02-music-portal\src\main\webapp\WEB-INF\music-servlet.xml
	
	// helper for delete and reload operations
	private PersistenceHelper persistence;
	
	private SecurityController securityController;
	
	// class of deleted object
	private Class<? extends PersistentEntity> clazz;
	
	// view where to navigate after completion
	private String viewName;
	
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) 
	throws Exception 
	{
		// delete object
		Long id = Long.parseLong(request.getParameter("id"));
		PersistentEntity entity = persistence.getById(clazz, id);
		
		//Check if current session, has rights to delete.
		if (entity instanceof SecuredEntity) {
			SecuredEntity securedEntity = (SecuredEntity) entity;
			securityController.updateSecurityStatus(request, securedEntity);
			if (! securedEntity.getUpdateGranted()) {
				//Cannot delete
				return null;
			}
		}		
		
		persistence.delete(clazz, id);
		
		//reload page with list of objects
		List<PersistentEntity> list = persistence.findAll(clazz);
		ModelAndView result = new ModelAndView(viewName);		
		// note that model object name is the same as in ListAllPersonController 
		// and the same name appears in \lab02-music\lab02-music-portal\src\main\webapp\WEB-INF\jsp\person_listall.jsp
		result.addObject("list", list);
		return result;
	}

	public PersistenceHelper getPersistence() {
		return persistence;
	}

	public void setPersistence(PersistenceHelper persistence) {
		this.persistence = persistence;
	}
	
	public Class<? extends PersistentEntity> getClazz() {
		return clazz;
	}

	public void setClazz(Class<? extends PersistentEntity> clazz) {
		this.clazz = clazz;
	}

	public String getViewName() {
		return viewName;
	}

	public void setViewName(String viewName) {
		this.viewName = viewName;
	}
	public SecurityController getSecurityController() {
		return this.securityController;
	}

	public void setSecurityController(
			SecurityController securityController) {
		this.securityController = securityController;
	}	
}
